package com.liu.manag.controller;

import com.alibaba.fastjson.JSONObject;
import com.liu.manag.config.HttpSessionConfiguration;
import com.liu.manag.entity.Message;
import com.liu.manag.service.MessageService;
import com.liu.manag.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Component
@ServerEndpoint(value = "/chat/{id}", configurator = HttpSessionConfiguration.class)
public class WebsocketServerEndpoint {

    @Autowired
    private MessageService messageService;

    private Session session;


    //在线连接数
    private static long online = 0;

    //存放当前websocket对象的集合
    private static CopyOnWriteArraySet<WebsocketServerEndpoint> websocketServerEndpoints
             = new CopyOnWriteArraySet<>();

    private Long fromId = 0L;

    @OnOpen
    public void onOpen(Session session, @PathParam("id")Long id){
        log.info("连接成功");
        this.session = session;

        websocketServerEndpoints.add(this);

        addOnlineCount();
        fromId = id;
        log.info("有新的连接: id = "+id+", 当前在线人数为:"+getOnlineCount());

    }

    @OnClose
    public void onClose(){
        log.info("连接关闭");
        websocketServerEndpoints.remove(this);

        subOnlineCount();
        log.info("有连接关闭， 当前在线人数:"+getOnlineCount());
    }

    /**
     * 服务器接收客户端发来的消息
     */
    @OnMessage
    public void onMessage(String message){

    }

    @OnError
    public  void error(Throwable e){
        e.printStackTrace();
    }

    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public void sendTo(Long fromId,Long toId,String content) throws Exception {
        if(websocketServerEndpoints.size() < 1){
            throw new Exception("用户未上线");
        }
        boolean flag = false;

        for(WebsocketServerEndpoint endpoint : websocketServerEndpoints){
            try{
                if(endpoint.fromId.equals(toId)){
                    flag = true;
                    log.info(fromId+" 推送消息给:"+toId+",消息内容为:"+content);
                    Message message = new Message();
                    message.setFromId(fromId);
                    message.setToId(toId);
                    message.setContent(content);
                    message.setCreateTime(LocalDateTime.now());
                   messageService.addMessage(fromId,toId,content,message.getCreateTime());
                    String res = JSONObject.toJSONString(new Result<Message>(message));
                    endpoint.sendMessage(res);
                }
            }catch (Exception e){
                e.printStackTrace();
                continue;
            }
        }

    }

    private String getData(Long toId, String content){
        Message message = new Message();
        message.setContent(content);
        return null;
    }











    private void subOnlineCount(){
        WebsocketServerEndpoint.online--;
    }
    private synchronized long getOnlineCount(){
        return online;
    }

    public void addOnlineCount() {
        WebsocketServerEndpoint.online++;
    }













}
